﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Diagnostics;

using X360;
using X360.IO;
using X360.Other;
using X360.Profile;
using X360.STFS;

using Blam_Unity.Classes.Windows_Explorer;

namespace Blam_Unity.Forms
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Open valid and suppored Halo Reach file!";
            ofd.Filter = "Halo Reach Xbox 360 STFS Package (*.*)|*.*|Halo Reach Xbox 360 Executable File(*.xex)|*.xex";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                MojosIO mio = new MojosIO(ofd.FileName, Endian.Big);

                if (checkFileInfo.checkMagic(mio) == "CON ")
                {
                    if (checkFileInfo.checkCONType(mio) == "feature.film")
                    {
                        Forms.Halo_AA.Theater.frmCONFilm frmFilm = new Forms.Halo_AA.Theater.frmCONFilm();
                        frmFilm.fileName = ofd.FileName;
                        frmFilm.MdiParent = this;
                        frmFilm.Show();
                    }
                    else if (checkFileInfo.checkCONType(mio) == "gamestate.hdr")
                    {
                        MessageBox.Show("Unity currently doesn't support Halo Reach Campaign Saves!", "Unsupported file type.", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                    else if (checkFileInfo.checkCONType(mio) == "variant")
                    {
                        MessageBox.Show("Unity currently doesn't support Halo Reach Gametypes!", "Unsupported file type.", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                    else if (checkFileInfo.checkCONType(mio) == "sandbox.map")
                    {
                        MessageBox.Show("Unity currently doesn't support Halo Reach Usermaps!", "Unsupported file type.", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                }
                else if (checkFileInfo.checkMagic(mio) == "XEX2")
                {
                    if (checkFileInfo.checkXEXID(mio) == "4D53085B")
                    {
                        Forms.Halo_AA.gameAssetLevel.gameExecutable.multiSelect frmMultiSelect = new Halo_AA.gameAssetLevel.gameExecutable.multiSelect();
                        frmMultiSelect.isCompressed = checkFileInfo.checkXEXCompression(mio);
                        frmMultiSelect.MdiParent = this;
                        frmMultiSelect.Location = new Point((this.Width / 2), (this.Height / 2));
                        frmMultiSelect.Show();
                    }
                }
                else if (checkFileInfo.checkMagic(mio) == "_blf")
                {
                    if (checkFileInfo.checkBLFtype(mio) == "levl")
                    {
                        Forms.Halo_AA.gameAssetLevel.maps.info.frmMapInfo frmInfo = new Halo_AA.gameAssetLevel.maps.info.frmMapInfo();
                        frmInfo.MdiParent = this;
                        frmInfo.fileName = ofd.FileName;
                        frmInfo.Show();
                    }
                    else if (checkFileInfo.checkBLFtype(mio) == "mapi")
                    {
                        Forms.Halo_AA.gameAssetLevel.maps.images.frmMapImageBLF frmMapImage = new Forms.Halo_AA.gameAssetLevel.maps.images.frmMapImageBLF();
                        frmMapImage.MdiParent = this;
                        frmMapImage.fileName = ofd.FileName;
                        frmMapImage.Show();
                    }
                }
                else
                {
                    MessageBox.Show("The selected file is not a supported Halo Reach File!", "Unsupported file type.", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }

                mio.Flush();
                mio.Close();
            }
        }

        private void getFileInfoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild == null) { }
            else
            {
                string fileInfo = checkFileInfo.getFileDetails(quickTasks.removeFormTitle(ActiveMdiChild.Text));

                MessageBox.Show(fileInfo, "File Info!");
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Forms.Extra.frmAbout frmAbout = new Extra.frmAbout();
            frmAbout.MdiParent = this;
            frmAbout.Show();
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Forms.Extra.frmSettings frmSet = new Extra.frmSettings();
            frmSet.MdiParent = this;
            frmSet.Show();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild == null) { }
            else if (ActiveMdiChild.Text.StartsWith("Unity")) { }
            else if (ActiveMdiChild.Text.StartsWith("feature.film"))
            {
                Forms.Halo_AA.Theater.frmCONFilm frm = (Forms.Halo_AA.Theater.frmCONFilm)this.ActiveMdiChild;
                frm.saveCON();
            }
            else if (ActiveMdiChild.Text.StartsWith("mapinfo"))
            {
                Forms.Halo_AA.gameAssetLevel.maps.info.frmMapInfo frmMapInfo = (Forms.Halo_AA.gameAssetLevel.maps.info.frmMapInfo)this.ActiveMdiChild;
                frmMapInfo.saveMapInfo();
            }
        }

        private void resignAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form frm in MdiChildren)
            {
                if (quickTasks.formResignCheck(frm.Text) == true)
                {
                    string direc = quickTasks.removeFormTitle(frm.Text);

                    STFSPackage stfsPackage = new STFSPackage(direc, null);
                    if (Blam_Unity.Properties.Settings.Default.UseDefaultKV == true) { stfsPackage.FlushPackage(new RSAParams(@"KV.bin")); }
                    else { stfsPackage.FlushPackage(new RSAParams(Blam_Unity.Properties.Settings.Default.KVDirectory)); }
                    stfsPackage.CloseIO();
                }
            }
            MessageBox.Show("Resigned.", "Resigned.");
        }

        private void resignThisToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (quickTasks.formResignCheck(ActiveMdiChild.Text) == true)
            {
                string direc = quickTasks.removeFormTitle(ActiveMdiChild.Text);

                STFSPackage stfsPackage = new STFSPackage(direc, null);
                if (Blam_Unity.Properties.Settings.Default.UseDefaultKV == true) { stfsPackage.FlushPackage(new RSAParams(@"KV.bin")); }
                else { stfsPackage.FlushPackage(new RSAParams(Blam_Unity.Properties.Settings.Default.KVDirectory)); }
                stfsPackage.CloseIO();
                MessageBox.Show("Resigned.", "Resigned.");
            }
        }

        private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                WebClient wb = new WebClient();
                int ProdVir = Convert.ToInt16(ProductVersion.Replace(".", ""));
                string newer = wb.DownloadString("http://xeraxic.com/software/checkVersionInfo.php?appName=ProjectUnity&appVersion=" + ProdVir);

                if (newer == "no") { MessageBox.Show("You are running the latest version of Halo Reach - Armory\n\nCurrent Version: " + ProductVersion, "Update"); }
                else
                {
                    if (MessageBox.Show("There is a newer version avaiable, would you like to download it?", "Update!", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No) { }
                    else
                    {
                        string direc = Application.UserAppDataPath + "\\";

                        try { File.Delete(direc + "update.exe"); }
                        catch { }

                        wb.DownloadFile("http://xeraxic.com/software/updater.exe", direc + "update.exe");
                        wb.DownloadFile("http://xeraxic.com/software/dlLib/projectUnity/update.ini", direc + "update.ini");

                        IniFile ini = new IniFile(direc + "update.ini");

                        ini.IniWriteValue("File", "downloadURL", newer);
                        ini.IniWriteValue("File", "currentDirec", Application.StartupPath + "\\");
                        ini.IniWriteValue("File", "currentFileName", System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.Replace(Application.StartupPath + "\\", ""));

                        this.Dispose();

                        Process.Start(direc + "update.exe");
                    }
                }
            }
            catch { MessageBox.Show("Check your internet connection, cannot connect to xeraxic.com! Try again in a few minutes.", "Error!"); }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            if (Blam_Unity.Properties.Settings.Default.CheckforUpdates == true)
            {
                checkForUpdatesToolStripMenuItem_Click(sender, e);
            }

            Forms.Extra.frmIntro frmIntro = new Forms.Extra.frmIntro();
            frmIntro.MdiParent = this;
            frmIntro.Show();
        }
    }
}